<?php


namespace app\common\model;


use think\Model;

class NewsModel extends Model
{
    protected $name = 'news';


    /**
     * 获取分页列表
     * @param int $is_index_show 首页展示:0=否,1=是
     * @param string $mold 分类:company=公司新闻,industry=行业新闻
     * @param int $page 数据条数
     * @param int $limit 数据条数
     * @return array
     */
    public function getPageList(int $is_index_show, string $mold, int $page, int $limit): array
    {
        try {
            $where = [
                'status' => 1,
            ];
            if($is_index_show > 0){
                $where['is_index_show'] = $is_index_show;
            }
            $field = ['id','date','title','desc','content','image','read','createtime'];
            $order = [
                'createtime' => 'desc',
            ];
            if($mold){
                $where['mold'] = $mold;
            }
            $list = $this
                ->where($where)
                ->field($field)
                ->order($order)
                ->paginate($limit, false, ['page' => $page]);
            foreach ($list as $row){
                $row->desc = str_replace('&nbsp;','',strip_tags($row->content));
                $row->image = full_url($row->image);
            }
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => $list
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public function getDetail(int $id): array
    {
        try {
            $field = ['id','date','title','content','read','createtime'];
            $data = $this
                ->field($field)
                ->where(['id' => $id])
                ->find();
            $data->setInc('read');
            $prev = $this
                ->field($field)
                ->where(['id' => ['<',$id]])
                ->order('createtime','asc')
                ->find();
            $next = $this
                ->field($field)
                ->where(['id' => ['>',$id]])
                ->order('createtime','asc')
                ->find();
            return [
                'code' => 200,
                'msg' => '请求成功',
                'data' => [
                    'data' => $data,
                    'prev' => $prev,
                    'next' => $next,
                ]
            ];
        }catch (\Exception $e) {
            return [
                'code' => $e->getCode(),
                'msg' => $e->getMessage(),
                'data' => []
            ];
        }
    }


}